export function useLoader() {
  let linkElement, scriptElement;
  let Y = 665,
    z = 665;

  function loadCss(source) {
    removeExistingElement(`#pure-utils-css-${Y}`);
    Y += 1;

    return new Promise((resolve, reject) => {
      linkElement = document.createElement("link");
      linkElement.id = `pure-utils-css-${Y}`;
      linkElement.rel = "stylesheet";

      linkElement.onload = () => {
        resolve("success");
      };

      linkElement.onerror = error => {
        reject(error);
      };

      linkElement.href = source.src;
      document[source?.carrier ?? "head"].appendChild(linkElement);
    });
  }

  function loadScript(source) {
    removeExistingElement(`#pure-utils-script-${z}`);
    z += 1;

    return new Promise((resolve, reject) => {
      scriptElement = document.createElement("script");
      scriptElement.id = `pure-utils-script-${z}`;
      scriptElement.type = "text/javascript";

      scriptElement.onload = () => {
        resolve("success");
      };

      scriptElement.onerror = error => {
        reject(error);
      };

      scriptElement.src = source.src;
      document[source?.carrier ?? "head"].appendChild(scriptElement);
    });
  }

  function removeExistingElement(selector) {
    const existingElement = document.querySelector(selector);
    if (existingElement) {
      existingElement.remove();
    }
  }

  return {
    loadCss,
    loadScript
  };
}
